/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.entities.helper;

import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.regex.Pattern;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class CDataXMLStreamWriter extends XMLWriter {

	private static final Pattern XML_CHARS = Pattern.compile("[<>]");

	public CDataXMLStreamWriter(OutputStream out, OutputFormat format)
			throws UnsupportedEncodingException {
		super(out, format);
	}

	/* 
	 * 对需要CDATA的元素进行处理
	 * @see org.dom4j.io.XMLWriter#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		boolean useCData = XML_CHARS.matcher(new String(ch, start, length))
				.find();
		if (useCData) {
			setEscapeText(false);
			super.startCDATA();
		}
		super.characters(ch, start, length);
		if (useCData) {
			super.endCDATA();
			setEscapeText(true);
		}
	}

}
